package com.lixw.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * @ClassName: MybatisConfig
 * @Description:
 * @Author: xuweiLi
 * @Create: 2025/6/25 07:57
 **/
@PropertySource("classpath:jdbc.properties") //配置文件读取
@MapperScan(basePackages = "com.lixw.mapper") //需要扫描生成代理的接口所在包
@EnableTransactionManagement //开启声明式事务
public class MybatisConfig {

    @Autowired
    private Environment env;

    //druid数据源
    @Bean
    public DataSource dataSource() {
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(env.getProperty("jdbc.driverClassName"));
        ds.setUrl(env.getProperty("jdbc.url"));
        ds.setUsername(env.getProperty("jdbc.username"));
        ds.setPassword(env.getProperty("jdbc.password"));
        return ds;
    }

    //sqlSession会话工厂
    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        //数据源
        sqlSessionFactoryBean.setDataSource(dataSource());
        //加载本地配置文件 当前类路径的开始 mapper文件夹下的mybatis配置文件  对于现在的纯注解开发,一般没啥存在的必要了
        sqlSessionFactoryBean.setConfigLocation(new PathMatchingResourcePatternResolver().getResource("classpath:mybatis-config.xml"));
        //mapper.xml文件所在位置  所有类路径的开始 mapper文件夹下的 所有xml文件
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/*.xml"));
        return sqlSessionFactoryBean.getObject();
    }

    //Mapper扫描器 已被注解@MapperScan代替 具体参见: org.mybatis.spring.annotation.MapperScannerRegistrar

    //数据源管理器,mybatis的事务交由spring来管理
    @Bean
    public PlatformTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }

}